<template>
  <el-card class="h-100">
    <div class="auth-top">
      <el-input disabled :value="route.query.roleName"></el-input>
      <el-form-item class="mt-10">
        <el-button type="primary" @click="assignToRole">保存</el-button>
        <el-button @click="router.back()">取消</el-button>
      </el-form-item>
    </div>
    <el-tree
      @check="checkChange"
      ref="treeRef"
      :data="allAuthList"
      show-checkbox
      default-expand-all
      node-key="id"
      :props="{
        children: 'children',
        label: 'name',
      }"
    />
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'RoleAuth',
}
</script>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getMenuByRoleApi, doAssignApi } from '@/api/menu/menuApi'
import { ElMessage, ElTree } from 'element-plus'
import type { MenuItem } from '@/api/menu/model/menuType'
import type { assign } from 'lodash'

const route = useRoute()
const router = useRouter()

const allAuthList = ref<MenuItem[]>([])
const checkedAuthList = ref<string[]>([])

// 封装函数
const getCheckedList = (children: MenuItem[]) => {
  let checked: string[] = []

  children.forEach((auth) => {
    if (auth.children?.length) {
      const childList = getCheckedList(auth.children as MenuItem[])
      if (childList.length === auth.children?.length) {
        checked.push(auth.id)
      } else if (childList.length) {
        checked = [...checked, ...childList]
      }
    } else {
      if (auth.select) {
        checked.push(auth.id)
      }
    }
  })
  return checked
}

// 组件挂载请求数据
onMounted(async () => {
  const res = await getMenuByRoleApi(route.query.id as string)
  allAuthList.value = res.children
  checkedAuthList.value = getCheckedList(res.children)
  // 设置选中的权限
  treeRef.value.setCheckedKeys(checkedAuthList.value)
})

const treeRef = ref() // 树形图的示例

// 点击选择框的回调
const checkChange = (
  item: MenuItem,
  { checkedKeys }: { checkedKeys: string[] }
) => {
  // console.log(checkedKeys)
  console.log(item)
  checkedAuthList.value = checkedKeys
}

// 保存按钮发送请求
const assignToRole = async () => {
  if (!checkedAuthList.value.length) return
  const half = treeRef.value.getHalfCheckedKeys()
  await doAssignApi(route.query.id as string, [
    ...checkedAuthList.value,
    ...half,
  ])
  ElMessage.success('添加权限成功')
  router.back()
}
</script>

<style scoped></style>
<style>
.mt-10 {
  margin-top: 10px;
}
.auth-top {
  position: sticky;
  background-color: #fff;
  top: 0px;
  z-index: 999;
  padding-top: 10px;
  border-bottom: 1px solid #eee;
}
.h-100 {
  height: 800px;
  overflow: auto;
}
</style>
